import {
  getAppList
} from '@/api/login';
// import { getGlobal } from '@/utils/global';
import {
  searchFilesList,
  downFile
} from '@/utils/getFiles';
// import {
//   GET_FILE_URL
// } from '@/api/login';
const changeBg = (type, data) => {
  // 对应的标签id
  const bgMap = {
    sysBg: 'MainBackgroundArea'
  };
  if (type in bgMap) {
    const eles = document.querySelectorAll(`#${bgMap[type]}`);
    eles.forEach((ele) => {
      ele.style.backgroundImage = `url(${data})`;
    });
  }
};

const state = {
  upPic: {
    sysLogo: {
      pic: '',
      id: 'S0001',
      name: 'sysLogo'
    },
    sysBg: {
      pic: '',
      id: 'S0002',
      name: 'sysBg'
    },
    sysLogoMain: {
      pic: '',
      id: 'S0006',
      name: 'sysLogoMain'
    },
    sysTheFontAfterLogo: {
      pic: '',
      id: 'S0007',
      name: 'sysTheFontAfterLogo'
    },
    sysLabel: {
      pic: '',
      id: 'S0008',
      name: 'sysLabel'
    }
  },
  mainIconUrl: '',
  appName: '',
  copyright: '',
  appId: '',
  qrConfig: ''
};

const mutations = {
  setUpPic: (state, {
    key,
    res
  }) => {
    state.upPic[key].pic = res;
  },
  setAppName: (state, name) => {
    state.appName = name;
    document.title = name;
  },
  setMainIconUrl: (state, url) => {
    state.mainIconUrl = url;
    const link = document.querySelector('link[rel="icon"]');
    link && (link.href = url);
  },
  setCopyright: (state, { copyright, id, qrConfig },) => {
    state.copyright = copyright;
    state.appId = id;
    state.qrConfig = qrConfig;
  }
};

const actions = {
  // 获取对应的系统页面
  getFiles: async({
    commit,
    state
  }) => {
    // if (state.upPic.sysLogo.pic !== '') {
    //   return;
    // }
    const ENV = process.env.NODE_ENV;
    const { data } = await getAppList({
      // position: ENV === 'development' ? 'xcjc' : window.location.href.split('/')[3]
      // position: ENV === 'development' ? 'ycjc' : window.location.href.split('/')[3]
      position: ENV === 'development' ? 'capital' : window.location.href.split('/')[3]
      // position: ENV === 'development' ? 'ggcj' : window.location.href.split('/')[3]
    });
    localStorage.setItem('themeColor', data.themeColor ? data.themeColor : '#006acd');

    commit('setCopyright', data);
    const appId = data.id;

    if (appId + '' !== localStorage.getItem('appId') && !localStorage.getItem('manySys')) {
    // 清除session
      sessionStorage.clear();
      localStorage.setItem('appId', appId);
    }
    if (appId) {
      for (const key in state.upPic) {
        const localRes = sessionStorage.getItem(key);
        // if (key === 'sysLogoMain') {
        //   const fileMainLogoUrl = sessionStorage.getItem(key + 'Url');
        //   fileMainLogoUrl && commit('setMainIconUrl', fileMainLogoUrl);
        // }
        if (localRes) {
          commit('setUpPic', {
            key,
            res: localRes
          });
          changeBg(key, localRes);
        } else {
          searchFilesList({
            appId,
            type: state.upPic[key].id
          }).then(async(fileInfo) => {
            const data = fileInfo.data && fileInfo.data[0];
            if (data) {
              // todo 开始下载文件
              downFile(data, 'pic').then((res) => {
                // res = res.split(',')[1];
                if (data.fileType === 'png') {
                  res = 'data:image/png;base64,' + res.split(',')[1];
                } else {
                  res = 'data:image/svg+xml;base64,' + res.split(',')[1];
                }
                sessionStorage.setItem(key, res);
                commit('setUpPic', {
                  key,
                  res
                });
                changeBg(key, res);
              });
              // todo 更换浏览器tab图标
              // if (key === 'sysLogoMain') {
              //   getGlobal().then((all) => {
              //     const baseURL = all.url;
              //     const fileMainLogoUrl = `${baseURL + GET_FILE_URL}?id=${
              //       data.id
              //     }&fileName=${data.saveName}`;
              //     commit('setMainIconUrl', fileMainLogoUrl);
              //     sessionStorage.setItem(key + 'Url', fileMainLogoUrl);
              //   });
              // }
            }
          });
        }
      }
    }
  },
  changeUppic: ({ commit }, id) => {
    if (id) {
      if (id + '' !== localStorage.getItem('appId')) {
        // 清除session
        localStorage.setItem('appId', id);
        localStorage.setItem('manySys', true);
      }
      for (const key in state.upPic) {
        if (key === 'sysLogoMain' || key === 'sysTheFontAfterLogo') {
          searchFilesList({
            appId: id,
            type: state.upPic[key].id
          }).then(async(fileInfo) => {
            const data = fileInfo.data && fileInfo.data[0];
            if (data) {
              // todo 开始下载文件
              downFile(data, 'pic').then((res) => {
                // res = res.split(',')[1];
                if (data.fileType === 'png') {
                  res = 'data:image/png;base64,' + res.split(',')[1];
                } else {
                  res = 'data:image/svg+xml;base64,' + res.split(',')[1];
                }
                sessionStorage.setItem(key, res);
                commit('setUpPic', {
                  key,
                  res
                });
                changeBg(key, res);
              });
              // todo 更换浏览器tab图标
              // if (key === 'sysLogoMain') {
              //   getGlobal().then((all) => {
              //     const baseURL = all.url;
              //     const fileMainLogoUrl = `${baseURL + GET_FILE_URL}?id=${
              //       data.id
              //     }&fileName=${data.saveName}`;
              //     commit('setMainIconUrl', fileMainLogoUrl);
              //     sessionStorage.setItem(key + 'Url', fileMainLogoUrl);
              //   });
              // }
            }
          });
        }
      }
    }
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
